package com.origin.netlibrary

import androidx.lifecycle.ViewModel
import com.origin.utils.log.LogUtils
import kotlinx.coroutines.CoroutineScope
import retrofit2.Call

/**
 * 完成主动清理和被动清理
 */
object NetStack {
    private var vmMapCall = mutableMapOf<CoroutineScope, MutableList<Call<*>>>()
    private var callMapVm = mutableMapOf<Call<*>, CoroutineScope>()
    public fun saveVmMapCall(vm: CoroutineScope, call: Call<*>) {
        if (!vmMapCall.containsKey(vm)) {
            val callList = mutableListOf<Call<*>>()
            callList.add(call)
            vmMapCall[vm] = callList
        } else {
            vmMapCall[vm]?.add(call)
        }
        if (!callMapVm.containsKey(call)) {
            callMapVm[call] = vm
        } else {
            LogUtils._e("NetStackYang call 对应重复的 vm")
        }
//        LogUtils._e("NetStackYang 保存后  vmMapCall 长度 ${vmMapCall.size}")
//        LogUtils._e("NetStackYang 保存后  callMapVm 长度 ${callMapVm.size}")
    }

    public fun clearByCall(call: Call<*>) {
        if (!callMapVm.containsKey(call)) {
            LogUtils._e("NetStackYang call 没有加入监听")
            return
        }
        vmMapCall[callMapVm[call]]?.apply {
            this.remove(call)
            if (this.size == 0) {
                vmMapCall.remove(callMapVm[call])
            }
        }
        callMapVm.remove(call)
//        LogUtils._e("NetStackYang clearByCall后  vmMapCall 长度 ${vmMapCall.size}")
//        LogUtils._e("NetStackYang clearByCall后  callMapVm 长度 ${callMapVm.size}")
    }

    public fun clearByVm(vm: CoroutineScope) {
        if (!vmMapCall.containsKey(vm)) {
            LogUtils._e("NetStackYang 这vm 没有加入监听或者没有任何网络请求，请检查业务")
            return
        }
        vmMapCall[vm]?.onEach {
            if (callMapVm.containsKey(it)) {
                callMapVm.remove(it)
            }
            it.cancel()
        }
        vmMapCall.remove(vm)
        LogUtils._e("NetStackYang clearByVm后  vmMapCall 长度 ${vmMapCall.size}")
        LogUtils._e("NetStackYang clearByVm后  callMapVm 长度 ${callMapVm.size}")
    }
}